<?php

namespace App\Jobs\Plane\Query;

use App\Trip\Enums\Plane\PlaneProviders;
use App\Trip\Plane\Requests\TicketQueryRequest;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;

class ProcessMixedTicketQuery implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int                 $timeout = 10;
    private TicketQueryRequest $request;
    private PlaneProviders     $provider;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(string $provider, string $request_param_key)
    {
        $this->request  = Cache::get($request_param_key);
        $this->provider = PlaneProviders::from($provider);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $service   = $this->provider->getPlaneQueryStrategy();
        $res       = $service->ticket_query($this->request);
        $cache_key = "{$this->request->getRequestParamKey()}:{$this->provider->value}";
        Cache::put($cache_key, $res->getLists(), 10 * config('trip.ttl.minutes'));
    }

    public function uniqueId()
    {
        return $this->provider->value.":".$this->request->getRequestParamKey();
    }

}
